﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.IO;
using DeepTime.DL;
using DeepTime.DataSources.DL;
using DeepTime.DL.DataModels;

namespace DeepTime.Web
{
    public partial class Image : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //
            // Check request type
            //
            if (Request.RequestType == "POST")
            {
                SaveInputStreamToBlob();
            }
            else if (Request.RequestType == "GET")
            {
                if (Request.QueryString["bloburi"] == null)
                {
                    WriteResponse("error,bloburi not in query string", "text/plain");
                }
                else
                {
                    GetOutputStreamFromBlob(Request.QueryString["bloburi"]);
                }
            }
        }

        /// <summary>
        /// Get a blob and write to response
        /// </summary>
        private void GetOutputStreamFromBlob(string BlobUID)
        {
            CloudBlockBlob Blob;
            string ContentType;
            //string FileName;
            string Encoding;

            try
            {
                //
                // Get to blob
                //
                UploadedImageDataSource uploadedImageDataSource = new UploadedImageDataSource();
                Blob = uploadedImageDataSource.Select(BlobUID);

                //
                // Get Metadata and properties of blob
                //
                Blob.FetchAttributes();
                
                //FileName = Blob.Metadata["FileName"];
                ContentType = Blob.Properties.ContentType;
                Encoding = Blob.Properties.ContentEncoding; ;
            }
            catch (Exception e)
            {
                WriteResponse("error," + e.Message.Replace(',', ' '), "text/plain");
                return;
            }

            //
            // Write successful response
            //
            WriteResponse(Blob.DownloadByteArray(), ContentType);
        }

        /// <summary>
        /// Saves the current input stream to a blob
        /// </summary>
        private void SaveInputStreamToBlob()
        {
            CloudBlockBlob Blob;
            UploadedImageMetaDataDataModel Img;

            try
            {
                //
                // Write to blob
                //
                UploadedImageDataSource uploadedImageDataSource = new UploadedImageDataSource();
                string BlobUID = System.Guid.NewGuid().ToString().ToLower();
                uploadedImageDataSource.Insert(Request.InputStream, BlobUID, out Blob);

                //
                // Set Metadata and properties of blob
                //
                //Blob.Metadata["FileName"] = "";
                //Blob.SetMetadata();

                Blob.Properties.ContentType = "image/jpeg";//Request.ContentType;
                Blob.Properties.ContentEncoding = Request.ContentEncoding.EncodingName;
                Blob.SetProperties();

                //
                // Write image metadata to table
                //
                Img = new UploadedImageMetaDataDataModel()
                {
                    PartitionKey = "1",
                    RowKey = System.Guid.NewGuid().ToString(),
                    Timestamp = DateTime.Now,
                    BlobUri = Blob.Uri.OriginalString,
                };

                UploadedImageMetaDataDataSource DataSource = new UploadedImageMetaDataDataSource();
                DataSource.Insert(Img);

                //
                // Add to queue for deepzoom processing
                //
                ImageProcessorQueueDataSource imageProcessorQueueDataSource = new ImageProcessorQueueDataSource();
                imageProcessorQueueDataSource.Insert(Img.PartitionKey, Img.RowKey);
            }
            catch (Exception e)
            {
                WriteResponse("error," + e.Message.Replace(',', ' '), "text/plain");
                return;
            }

            //
            // Write successful response
            //
            WriteResponse("success,return data goes here", "text/plain");
        }

        /// <summary>
        /// Writes a reponse
        /// </summary>
        /// <param name="data">The text to write</param>
        /// <param name="contentType">Content Type</param>
        private void WriteResponse(string data, string contentType)
        {
            Page.Response.Clear();
            Page.Response.ContentType = contentType;
            Page.Response.Write(data);
            Page.Response.End();
        }

        /// <summary>
        /// Writes a reponse
        /// </summary>
        /// <param name="data">The stream to write</param>
        /// <param name="contentType">Content Type</param>
        private void WriteResponse(byte[] data, string contentType)
        {
            Page.Response.Clear();
            Page.Response.ContentType = contentType;
            Page.Response.BinaryWrite(data);
            Page.Response.End();
        }
    }
}